package com.project.XXXX.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.project.XXXX.inter.tbl_dictMapper;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.project.XXXX.api.EmployerManage;
import com.project.XXXX.controllerInterface.IJobManager;
import com.project.XXXX.identification.tool.ValidateTool;
import com.project.XXXX.inter.tbl_divisionMapper;
import com.project.XXXX.inter.tbl_employerinfoMapper;
import com.project.XXXX.inter.tbl_jobenrollMapper;
import com.project.XXXX.inter.tbl_ptjobMapper;
import com.project.XXXX.inter.tbl_sysuserMapper;
import com.project.XXXX.inter.tbl_workplaceMapper;
import com.project.XXXX.inter.tbl_worktimeMapper;
import com.project.XXXX.model.tbl_employeeinfo;
import com.project.XXXX.model.tbl_employerinfo;
import com.project.XXXX.model.tbl_ptjobWithBLOBs;
import com.project.XXXX.model.tbl_sysuser;
import com.project.XXXX.model.tbl_workplace;
import com.project.XXXX.model.tbl_worktime;
import com.project.XXXX.stringmodel.PtJobAddress;
import com.project.XXXX.stringmodel.PtJobForShown;
import com.project.XXXX.stringmodel.PtJobTime;
import com.project.XXXX.tools.ProjectTools;

@Controller
public class JobManagerControllerImpl implements IJobManager {
	@Resource
	private tbl_ptjobMapper tbl_ptjobMapper;
	@Resource
	private tbl_sysuserMapper tbl_sysuserMapper;
	@Resource
	private tbl_employerinfoMapper tbl_employerinfoMapper;
	@Resource
	private tbl_worktimeMapper tbl_worktimeMapper;
	@Resource
	private tbl_dictMapper tbl_dictMapper;
	@Resource
	private tbl_jobenrollMapper tbl_jobenrollMapper;
	@Resource
	private tbl_divisionMapper tbl_divisionMapper;
	@Resource
	private tbl_workplaceMapper tbl_workplaceMapper;

	@RequestMapping(value = "/JobPost.do", method = RequestMethod.POST)
	public void PostJob(HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
	
		List<PtJobAddress> lworkplace;
		tbl_ptjobWithBLOBs record = new tbl_ptjobWithBLOBs();
		String json = request.getParameter("jobplace");
		Gson gson = new Gson();
		lworkplace = gson.fromJson(json, new TypeToken<List<PtJobAddress>>() {
		}.getType());
		record.setTitle(request.getParameter("title"));
		record.setCreatetime(new Date());
		record.setPersonnum(Integer.valueOf(request.getParameter("personnum")));
		record.setSalaryunit(Integer.valueOf(request.getParameter("salaryunit")));
		record.setGenderneedid(Integer.valueOf(request.getParameter("genderneedid")));
		record.setCityid(Integer.valueOf(request.getParameter("s_county")));
		if (request.getParameter("billcycleid") != null)
			record.setBillcycleid(Integer.valueOf(request.getParameter("billcycleid")));
		record.setPttypeid(Integer.valueOf(request.getParameter("pttypeid")));
		if (request.getParameter("salary") != null)
			record.setSalary(BigDecimal.valueOf(Double.valueOf(request.getParameter("salary"))));
		if (request.getParameter("PhoneNum") == null)
			record.setMobile(request.getParameter("PhoneNum"));
		else
			record.setMobile(tbl_sysuser.getMobile());
		record.setRequirement(request.getParameter("requirement"));
		record.setContect(request.getParameter("contect"));
		record.setCreatorid(tbl_sysuser.getMobile());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
		Date begindate = null, enddate = null;
		try {
			begindate = sdf.parse(request.getParameter("beginDate"));
			enddate = sdf.parse(request.getParameter("endDate"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		record.setBegindate(begindate);
		record.setEnddate(enddate);
		record.setTimebegin(request.getParameter("timebegin"));
		record.setTimeend(request.getParameter("timeend"));
		record.setStatus(27);
	
		record.setInterview(Integer.parseInt(request.getParameter("interview")));
		record.setTrain(Integer.parseInt(request.getParameter("train")));

		if (request.getParameter("id") != null) {
			record.setId(Integer.parseInt(request.getParameter("id")));
			record.setModifytime(new Date());
			tbl_ptjobMapper.updateByPrimaryKeySelective(record);
			tbl_workplaceMapper.deleteBytbl_ptjob_id(record.getId());
			for (PtJobAddress p : lworkplace) {
				tbl_workplace t = new tbl_workplace();
				t.setJobplace(p.getAddress() + "&" + p.getDetailAddress());
				t.setLat(p.getLat());
				t.setLng(p.getLng());
				t.setDivisionid(p.getCountrycode());
				t.setTblPtjobId(record.getId());
				tbl_workplaceMapper.insert(t);
			}
		} else {
		
			tbl_ptjobMapper.insertSelective(record);
			List<tbl_ptjobWithBLOBs> l = tbl_ptjobMapper.SelectAllbyuserId(record.getMobile());
			record = l.get(0);
			tbl_workplaceMapper.deleteBytbl_ptjob_id(record.getId());
			for (PtJobAddress p : lworkplace) {
				tbl_workplace t = new tbl_workplace();
				t.setJobplace(p.getAddress() + "&" + p.getDetailAddress());
				t.setLat(p.getLat());
				t.setLng(p.getLng());
				t.setDivisionid(p.getCountrycode());
				t.setTblPtjobId(record.getId());
				tbl_workplaceMapper.insert(t);
			}
		}
		try {
			response.sendRedirect("ERIndex.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping("/showERPtJobList.do")
	public void showERPtJobs(HttpServletRequest request, HttpServletResponse response, Model model,
			HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
		tbl_employerinfo tbl_employerinfo = tbl_employerinfoMapper.selectByPrimaryKey(tbl_sysuser.getMobile());
		List<tbl_ptjobWithBLOBs> list = null;

		int pageSize = 5;
		int currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));

		currentPage = (currentPage - 1) * pageSize;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("creatorid", tbl_sysuser.getMobile());
		map.put("status", 27);
		map.put("pagesize", pageSize);
		map.put("offset", currentPage);
		list = tbl_ptjobMapper.getDiffStautsPtJob(map);

		int pageCountNums = list == null ? 0 : list.size();
		if (pageCountNums == 0) {
			map.clear();
			map.put("state", "success");
			map.put("success_description", "no data");
			ProjectTools.ResponseOut(response, new Gson().toJson(map));
		} else {
			List<PtJobForShown> l = new ArrayList<PtJobForShown>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String pttypeid;
			String cityid;
			String salaryunit;
			String billcycleid;
			for (tbl_ptjobWithBLOBs job : list) {
				cityid = job.getCityid() + "";
				cityid = tbl_divisionMapper.selectCountryName(cityid).getDiming();
				salaryunit = tbl_dictMapper.selectByPrimaryKey(job.getSalaryunit()).getValue();
				pttypeid = tbl_dictMapper.selectByPrimaryKey(job.getPttypeid()).getValue();
				billcycleid = tbl_dictMapper.selectByPrimaryKey(job.getBillcycleid()).getValue();
				String Genderne = tbl_dictMapper.selectByPrimaryKey(job.getGenderneedid()).getValue();
				int applyed,confirmed;
				map.put("ptjobid", job.getId());
				map.put("status", 30);
				applyed = tbl_jobenrollMapper.getReqJobUserCount(map);
				map.clear();
				map.put("ptjobid", job.getId());
				map.put("status", 31);
				confirmed = tbl_jobenrollMapper.getReqJobUserCount(map);
				PtJobForShown ptjob = new PtJobForShown(job.getId() + "",

						job.getMobile(), job.getTitle(), pttypeid, cityid, sdf.format(job.getBegindate()),
						sdf.format(job.getEnddate()), job.getPersonnum() + "", Genderne, job.getSalary() + "",
						salaryunit, billcycleid, sdf.format(job.getCreatetime()), job.getInterview() + "",
						job.getTrain() + "", job.getTimebegin() + "", job.getTimeend(),tbl_employerinfo.getLogo()
						,applyed,confirmed);
				l.add(ptjob);

			}

			String json;
			Gson gson = new Gson();
			json = gson.toJson(l);
			ProjectTools.ResponseOut(response, json);
		}

	}

	@RequestMapping("/showPtJobCount.do")
	public void showPtJobsCount(HttpServletRequest request, HttpServletResponse response, Model model,
			HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
		int size = 0;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("creatorid", tbl_sysuser.getMobile());
		map.put("status", 27);

		size = tbl_ptjobMapper.getDiffStautsPtJobSize(map);

		ProjectTools.ResponseOut(response, "{\"CountNums\":\"" + size + "\"}");

	}
	@RequestMapping("/startagain.do")
	public void startagain(@RequestParam("id") int id, HttpServletRequest request, HttpServletResponse response,
			Model model, HttpSession session) {
		tbl_ptjobWithBLOBs tbl_ptjobWithBLOBs = tbl_ptjobMapper.selectByPrimaryKey(id);
		if (tbl_ptjobWithBLOBs == null) {
			tbl_ptjobWithBLOBs = new tbl_ptjobWithBLOBs();
		}
		tbl_ptjobWithBLOBs.setId(null);
		tbl_ptjobWithBLOBs.setBegindate(new Date());
		tbl_ptjobWithBLOBs.setEnddate (new Date());
		List<PtJobAddress> lworkspace = new ArrayList<>();
		for (tbl_workplace x : tbl_workplaceMapper.selectJobId(Integer.parseInt(request.getParameter("id")))) {
			String address[] = x.getJobplace().split("&");
			PtJobAddress p = new PtJobAddress(x.getLat(), x.getLng(), address[0], x.getDivisionid(), address[1], false);
			lworkspace.add(p);
		}

		session.setAttribute("ptJobworkspace", lworkspace);
		session.setAttribute("ptJob", tbl_ptjobWithBLOBs);
		ProjectTools.ResponseOut(response, "{\"opstatus\":\"" + true + "\"}");
	}
	@RequestMapping(value = "/editPtJob.do", method = RequestMethod.POST)
	public void editPtJob(@RequestParam("id") int id, HttpServletRequest request, HttpServletResponse response,
			Model model, HttpSession session) {
		tbl_ptjobWithBLOBs tbl_ptjobWithBLOBs = tbl_ptjobMapper.selectByPrimaryKey(id);
		if (tbl_ptjobWithBLOBs == null) {
			tbl_ptjobWithBLOBs = new tbl_ptjobWithBLOBs();
		}
		List<PtJobAddress> lworkspace = new ArrayList<>();
		for (tbl_workplace x : tbl_workplaceMapper.selectJobId(Integer.parseInt(request.getParameter("id")))) {
			String address[] = x.getJobplace().split("&");
			PtJobAddress p = new PtJobAddress(x.getLat(), x.getLng(), address[0], x.getDivisionid(), address[1], false);
			lworkspace.add(p);
		}

		session.setAttribute("ptJobworkspace", lworkspace);
		session.setAttribute("ptJob", tbl_ptjobWithBLOBs);
		ProjectTools.ResponseOut(response, "{\"opstatus\":\"" + true + "\"}");

	}

	@RequestMapping(value = "/deletePtJob.do", method = RequestMethod.POST)
	public void deletePtJob(@RequestParam("id") int id, HttpServletRequest request, HttpServletResponse response,
			Model model, HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
		tbl_ptjobWithBLOBs record = tbl_ptjobMapper.selectByPrimaryKey(id);
		String json;
		Map<String, Object> map = new HashMap<String, Object>();
		if (record != null && (record.getStatus() != 41)) {
			record.setStatus(41);
			tbl_ptjobMapper.updateByPrimaryKeySelective(record);
			map.put("state", "success");
			map.put("success_description", "delete success");

		} else {
			map.put("state", "error");
			map.put("error_description", "permission error");
		}

		json = new Gson().toJson(map);
		ProjectTools.ResponseOut(response, json);

	}

	@RequestMapping("/getDiffStatusPtJob.do")
	public void getDiffStatusPtJob(HttpServletRequest request, HttpServletResponse response, Model model,
			HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
		tbl_employerinfo tbl_employerinfo = tbl_employerinfoMapper.selectByPrimaryKey(tbl_sysuser.getMobile());
		int pageSize = 10;
		String json;
		int currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
		currentPage = (currentPage - 1) * pageSize;
		int status = Integer.parseInt(request.getParameter("status"));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("creatorid", tbl_sysuser.getMobile());
		map.put("status", status);
		map.put("pagesize", pageSize);
		map.put("offset", currentPage);
		List<tbl_ptjobWithBLOBs> list = tbl_ptjobMapper.getDiffStautsPtJob(map);
		List<PtJobForShown> l = new ArrayList<PtJobForShown>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String pttypeid;
		String cityid;
		String salaryunit;
		String billcycleid;
		
		for (tbl_ptjobWithBLOBs job : list) {
			cityid = job.getCityid() + "";
			cityid = tbl_divisionMapper.selectCountryName(cityid).getDiming();
			salaryunit = tbl_dictMapper.selectByPrimaryKey(job.getSalaryunit()).getValue();
			pttypeid = tbl_dictMapper.selectByPrimaryKey(job.getPttypeid()).getValue();
			billcycleid = tbl_dictMapper.selectByPrimaryKey(job.getBillcycleid()).getValue();
			String Genderne = tbl_dictMapper.selectByPrimaryKey(job.getGenderneedid()).getValue();
			int applyed,confirmed;
			map.put("ptjobid", job.getId());
			map.put("status", 30);
			applyed = tbl_jobenrollMapper.getReqJobUserCount(map);
			map.clear();
			map.put("ptjobid", job.getId());
			map.put("status", 31);
			confirmed = tbl_jobenrollMapper.getReqJobUserCount(map);
			PtJobForShown ptjob = new PtJobForShown(job.getId() + "",

					job.getMobile(), job.getTitle(), pttypeid, cityid, sdf.format(job.getBegindate()),
					sdf.format(job.getEnddate()), job.getPersonnum() + "", Genderne, job.getSalary() + "", salaryunit,
					billcycleid, sdf.format(job.getCreatetime()), job.getInterview() + "", job.getTrain() + "",
					job.getTimebegin() + "", job.getTimeend(),tbl_employerinfo.getLogo(),applyed,confirmed);

			l.add(ptjob);

		}

		Gson gson = new Gson();
		json = gson.toJson(l);
		ProjectTools.ResponseOut(response, json);

	}

	@RequestMapping("/showPtJobWithStatusCount.do")
	public void showPtJobWithStatusCount(HttpServletRequest request, HttpServletResponse response, Model model,
			HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
		int size = 0;
		int status = Integer.parseInt(request.getParameter("status"));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("creatorid", tbl_sysuser.getMobile());
		map.put("status", status);
		size = tbl_ptjobMapper.getDiffStautsPtJobSize(map);
		ProjectTools.ResponseOut(response, "{\"CountNums\":\"" + size + "\"}");

	}

	@RequestMapping(value = "/changeJobStatus.do", method = RequestMethod.POST)
	public void changeJobStatus(@RequestParam("status") int status, @RequestParam("ptid") int ptid,
			HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {
		tbl_sysuser tbl_sysuser = (tbl_sysuser) session.getAttribute("User");
		tbl_ptjobWithBLOBs record = tbl_ptjobMapper.selectByPrimaryKey(ptid);
		String json;
		Map<String, Object> map = new HashMap<String, Object>();
		if (record != null && (record.getStatus() != status)) {
			if (ValidateTool.IsJobEnroll(tbl_sysuser, tbl_jobenrollMapper, ptid)
					|| ValidateTool.IsMyJob(tbl_sysuser, tbl_ptjobMapper, ptid)) {
				record.setStatus(status);
				record.setId(ptid);
				tbl_ptjobMapper.updateByPrimaryKeySelective(record);
				map.put("state", "success");
				map.put("success_description", "delete success");
			}
		}else {
			map.put("state", "error");
			map.put("error_description", "permission error");
	
		}
	
	

	json = new Gson().toJson(map);
	ProjectTools.ResponseOut(response, json);

	}

}
